package cn.edu.ncepu;

/**
 * 求根号2
 * 2025-11-11
 *
 * @author 醒过来摸鱼
 */
public class Sqrt {

    public static final double ERROR = 1e-15;

    public static void main(String[] args) {
        System.out.println(ERROR);
        double x = sqrt(14);
        System.out.println(x);
        System.out.println(x == Math.sqrt(14));
    }

    public static double sqrt(int y) {
        if (y < 1) {
            throw new IllegalArgumentException("请输入正整数");
        }

        int a = getA(y);
        int numerator = y - a * a;
        double x = 1d;
        while (true) {
            double newX = numerator / (2 * a + x);
            if (Math.abs(newX - x) < ERROR) {
                break;
            }
            x = newX;
        }
        return a + x;
    }

    private static int getA(int y) {
        int i = 0;
        while (i * i < y) {
            i++;
        }
        return i - 1;
    }
}